<template>
  <my-container>
    <!--查询-->
    <!-- <template #header>
      <el-form class="ad-form-query" :inline="true" :model="filter" @submit.native.prevent>

        <el-form-item>
          <el-select v-model="filter.wllb" filterable placeholder="请选择物料类型" style="width:100%;" @change="changeValue">
            <el-option
              v-for="item in xbcTypeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-input
            v-model="filter.wlCode"
            placeholder="物料号"
            clearable
            @keyup.enter.native="getXbcmaterrials"
          >
            <template #prefix>
              <i class="el-input__icon el-icon-search" />
            </template>
          </el-input>
        </el-form-item>
        <el-form-item v-if="checkPermission(['api:warehouse:xbcmaterrial:getpage'])">
          <el-button icon="el-icon-search" type="primary" @click="getXbcmaterrials">查询</el-button>
        </el-form-item>
        <el-form-item v-if="checkPermission(['api:warehouse:xbcmaterrial:batchsoftdelete'])">
          <my-confirm-button
            :disabled="sels.length === 0"
            :type="'delete'"
            :placement="'bottom-end'"
            :loading="deleteLoading"
            :validate="batchDeleteValidate"
            style="margin-left: 0px;"
            @click="onBatchDelete"
          >
            <template #content>
              <p>确定要批量删除吗？</p>
            </template>
            批量删除
          </my-confirm-button>
        </el-form-item>
      </el-form>
    </template> -->

    <vxe-grid
      ref="xGrid"
      border
      resizable
      :export-config="{
        modes:['current', 'selected']}"
      stripe
      auto-resize
      show-overflow
      size="small"
      height="auto"
      :toolbar="tableToolbar"
      :proxy-config="proxyConfig"
      :loading="listLoading"
      :columns="tableColumn"
    >

      <template v-slot:toolbar_buttons>
        <el-form class="ad-form-query" :inline="true" :model="filter" @submit.native.prevent>

          <el-form-item>
            <el-select v-model="filter.wllb" filterable placeholder="请选择物料类型" style="width:100%;" @change="changeValue">
              <el-option
                v-for="item in xbcTypeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-input
              v-model="filter.wlCode"
              placeholder="物料号"
              clearable
              @keyup.enter.native="getXbcmaterrials"
            >
              <template #prefix>
                <i class="el-input__icon el-icon-search" />
              </template>
            </el-input>
          </el-form-item>
          <el-form-item v-if="checkPermission(['api:warehouse:xbcmaterrial:getpage'])">
            <el-button icon="el-icon-search" type="primary" @click="getXbcmaterrials">查询</el-button>
          </el-form-item>
          <el-form-item v-if="checkPermission(['api:warehouse:xbcmaterrial:batchsoftdelete'])">
            <my-confirm-button
              :disabled="sels.length === 0"
              :type="'delete'"
              :placement="'bottom-end'"
              :loading="deleteLoading"
              :validate="batchDeleteValidate"
              style="margin-left: 0px;"
              @click="onBatchDelete"
            >
              <template #content>
                <p>确定要批量删除吗？</p>
              </template>
              批量删除
            </my-confirm-button>
          </el-form-item>
        </el-form>
      </template>
      <!-- :pager-config="{pageSize: 10}" -->
      <template v-if="checkPermission(['api:warehouse:stocklist:getdetailpage'])" v-slot:operate="{$index, row }">
        <vxe-button v-if="checkPermission(['api:warehouse:stocklist:getdetailpage'])" icon="fa fa-edit" title="明细" circle @click="onEdit($index,row)" />
      </template>
    </vxe-grid>

    <vxe-modal id="ssss" v-model="modalShow" width="950" height="670" min-width="460" min-height="320" resize remember storage transfer>
      <template v-slot:title>
        <span>库存明细</span>
      </template>
      <template>
        <!-- <el-form class="ad-form-query" :inline="true" :model="mfilter" @submit.native.prevent>
          <el-form-item>
            <el-input
              v-model="mfilter.wlCode"
              placeholder="物料号"
              clearable
              @keyup.enter.native="getStockInListPage"
            >
              <template #prefix>
                <i class="el-input__icon el-icon-search" />
              </template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-refresh" type="primary" @click="getStockInListPage">刷新</el-button>
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-plus" type="primary" @click="confirmselection">确认</el-button>
          </el-form-item>
        </el-form> -->
        <vxe-grid
          ref="mGrid"
          border
          resizable
          stripe
          auto-resize
          show-overflow
          size="small"
          height="auto"
          :export-config="{
            modes:['current', 'selected', 'all']}"
          :sync-resize="modalShow"
          :loading="mloading"
          :toolbar="mtableToolbar"
          :proxy-config="mproxyConfig"
          :seq-config="{startIndex: (tablePage.currentPage - 1) * tablePage.pageSize}"
          :pager-config="tablePage"
          :columns="mtableColumn"
          @page-change="pageChange"
        />
      </template>
    </vxe-modal>

  </my-container>
</template>

<script>
import XEUtils from 'xe-utils'
import { getxbcTypeList, getXbcTypeConf } from '@/api/warehouse/xbctype'
// import { removeXbcWarehouse, batchRemoveXbcWarehouse } from '@/api/warehouse/xbcwarehouse'
import { getxbcLocationList } from '@/api/warehouse/xbclocation'
import { getStockListPage, getAllPage, getStockDetailListPage, getAllDetailPage } from '@/api/warehouse/stocklist'
import MyContainer from '@/components/my-container'
import MyConfirmButton from '@/components/my-confirm-button'

export default {
  name: 'Stocklist',
  components: { MyContainer, MyConfirmButton },
  data() {
    return {
      filter: {
        // name: '',
        // xbcTypeId: null // 物料类别
        wlCode: '',
        wllb: null
      },
      conf: {
        isTerm: false, // 是否有效期
        isRegLlBatch: false, // 是否记录来料批次
        isSingle: false, // 是否单个入库
        isProduceNumb: false, // 是否生成编号
        prefix: '', // 编号前缀
        canReturn: false, // 是否要归还
        isThawWare: false, // 是否有解冻仓库
        isRegEquip: false, // 出库是否记录设备号
        isRegProduBatch: false, // 是否记录产品批号
        isRegMaterArriDate: false, // 是否记录来料日期
        isRegPcbLot: false, // 是否等级pcblot号
        showCustomCode: false // 是否显示客户代码
      },
      mfilter: {
        wlId: null, // 物料id
        kwId: null// 库位id wlId: this.filter.wlId, kwId: this.filter.kwId
      },
      tableToolbar: {
        export: true,
        custom: true,
        slots: {
          buttons: 'toolbar_buttons'
        }
      },
      mtableToolbar: {
        export: true,
        custom: true
      },
      cvisible: false,
      submitLoading: false,
      modalShow: false,
      roles: [],
      statusList: [
        { name: '激活', value: true },
        { name: '禁用', value: false }
      ],
      xbcTypeList: [], // 物料分类下拉
      xbcLocationList: [], // 库位下拉
      wlffdwList: [], // 物料最小发放单位
      wlffslList: [], // 物料最小发放数量
      khdmList: [], // 客户代码
      ckdwList: [], // 库存单位列表
      mproxyConfig: {
        // seq: true, // 启用动态序号代理
        // sort: true, // 启用排序代理
        // filter: true, // 启用筛选代理
        ajax: {
          // 任何支持 Promise API 的库都可以对接（fetch、jquery、axios、xe-ajax）
          query: async({ page, sort, filters, form }) => {
            // 处理排序条件
            const para = {
              currentPage: this.tablePage.currentPage,
              pageSize: this.tablePage.pageSize,
              filter: this.mfilter
            }
            this.mloading = true
            const res = await getStockDetailListPage(para)
            this.mloading = false
            this.tablePage.total = res.data.page.total
            if (!res?.success) {
              return
            }
            return res.data
          },
          // 被某些特殊功能所触发，例如：导出数据 mode=all 时，会触发该方法并对返回的数据进行导出
          queryAll: () => getAllDetailPage({ wlId: this.mfilter.wlId, kwId: this.mfilter.kwId
          })
        }
      },
      proxyConfig: {
        // seq: true, // 启用动态序号代理
        // sort: true, // 启用排序代理
        // filter: true, // 启用筛选代理
        ajax: {
          // 任何支持 Promise API 的库都可以对接（fetch、jquery、axios、xe-ajax）
          query: async({ page, sort, filters, form }) => {
            // 处理排序条件
            const para = {
              currentPage: 1, // page.currentPage
              pageSize: 1, // page.pageSize
              filter: this.filter
            }
            this.listLoading = true
            const res = await getStockListPage(para)
            this.listLoading = false

            if (!res?.success) {
              return
            }

            // this.tablePage.total = res.data.total
            // const data = res.data.list
            // data.forEach(d => {
            //   d._loading = false
            // })
            // console.log('ccc', res.data)
            return res.data.result
          },
          // 被某些特殊功能所触发，例如：导出数据 mode=all 时，会触发该方法并对返回的数据进行导出
          queryAll: () => getAllPage({ name: this.filter.name, id: this.filter.xbcTypeId
            // currentPage: 0,
            // pageSize: 0,
            // filter: this.filter
          })
          // async({ page }) => {
          //   // 处理排序条件
          //   const para = {
          //     currentPage: 0,
          //     pageSize: page.pageSize,
          //     filter: this.filter
          //   }
          //   this.listLoading = true
          //   const res = await getXbcmaterrialListPage(para)
          //   this.listLoading = false

          //   if (!res?.success) {
          //     return
          //   }

          //   // this.tablePage.total = res.data.total
          //   // const data = res.data.list
          //   // data.forEach(d => {
          //   //   d._loading = false
          //   // })
          //   return res.data.list
          // }
          // () => XEAjax.get('https://api.xuliangzhan.com:10443/api/pub/all')
        }
      },
      tableColumn: [
        { type: 'checkbox', width: 50 },
        { type: 'seq', width: 60 },
        { field: 'materrialCode', title: '物料号' },
        { field: 'materrialName', title: '物料名称' },
        { field: 'kwName', title: '库位' },
        { field: 'ckName', title: '仓库' },
        { field: 'kcDw', title: '单位' },
        { field: 'kcNum', title: '剩余数量' },
        { field: 'expiredNum', title: '过期数量', visible: false }, // this.conf.isTerm
        { field: 'matterrialId', title: 'wlid', visible: false },
        { field: 'locationId', title: 'kwid', visible: false }
      ],
      mtableColumn: [],
      tablePage: {
        total: 0,
        currentPage: 1,
        pageSize: 10
      },
      pager: {},
      listLoading: false,
      mloading: false,
      sels: [], // 列表选中列

      addDialogFormVisible: false,
      editFormVisible: false, // 编辑界面是否显示
      editLoading: false,
      // 编辑界面数据
      editForm: {
        id: 0,
        code: '',
        name: '',
        remark: '',
        xbcTypeId: '', // 物料类别
        xbcLocationId: '', // 库位id
        wlgg: '', // 物料规格
        khdmId: null, // 客户代码
        ckdwId: null, // 库存单位
        zxffslId: null, // 最小发放数量
        zxffdwId: null, // 最小发放单位
        lifeTime: 0, // 生命周期
        enabled: '',
        canChangeType: true
      },
      editFormRef: null,

      addFormVisible: false, // 新增界面是否显示
      addLoading: false,
      // 新增界面数据
      addForm: {
        code: '',
        name: '',
        remark: '',
        xbcTypeId: null, // 物料类别
        xbcLocationId: null, // 库位id
        wlgg: '', // 物料规格
        khdmId: null, // 客户代码
        ckdwId: null, // 库存单位
        zxffslId: null, // 最小发放数量
        zxffdwId: null, // 最小发放单位
        lifeTime: 0, // 生命周期
        enabled: true
      },
      addFormRef: null,
      deleteLoading: false
    }
  },
  mounted() {
    if (this.checkPermission(['api:warehouse:stocklist:getdetailpage'])) {
      this.tableColumn.push({ title: '明细', width: 100, slots: { default: 'operate' }})
    }
    this.getxbcTypeList()
    // this.$refs.xGrid.commitProxy('reload')
    // this.getXbcmaterrials()
  },
  methods: {
    formatDate({ cellValue }) {
      return XEUtils.toDateString(cellValue, 'yyyy-MM-dd')
    },
    async pageChange({ currentPage, pageSize }) {
      this.tablePage.currentPage = currentPage
      this.tablePage.pageSize = pageSize
    },
    // 汇总列表
    async  getXbcmaterrials() {
      console.log('conf', this.conf.isTerm)
      this.tableColumn = [
        { type: 'checkbox', width: 50 },
        { type: 'seq', width: 60 },
        { field: 'materrialCode', title: '物料号' },
        { field: 'materrialName', title: '物料名称' },
        { field: 'kwName', title: '库位' },
        { field: 'ckName', title: '仓库' },
        { field: 'kcDw', title: '单位' },
        { field: 'kcNum', title: '剩余数量' },
        { field: 'expiredNum', title: '过期数量', visible: this.conf.isTerm },
        { field: 'matterrialId', title: 'wlid', visible: false },
        { field: 'locationId', title: 'kwid', visible: false }
      ]
      if (this.checkPermission(['api:warehouse:stocklist:getdetailpage'])) {
        this.tableColumn.push({ title: '明细', width: 100, slots: { default: 'operate' }})
      }
      if (this.$refs.xGrid) {
        this.$nextTick(() => {
          this.$refs.xGrid.commitProxy('reload')
        })
      }

      // this.$refs.xGrid.commitProxy('reload')
    },
    async getxbcTypeList() {
      const res = await getxbcTypeList()
      if (res && res.success) {
        this.xbcTypeList = res.data
      }
    },

    async changeValue() {
      const res2 = await getXbcTypeConf({ id: this.filter.wllb })
      if (res2 && res2.success) {
        this.conf = res2.data
      }
    },
    // 显示编辑界面
    async onEdit(index, row) {
      // const loading = this.$loading()
      this.mtableColumn = [
        { type: 'seq', width: 60 },
        // { field: 'stockInId', title: '入库id', visible: false },
        // { field: 'materialCode', title: '物料编码', visible: this.conf.isProduceNumb },
        // { field: 'customerCode', title: '客户代码', visible: this.conf.showCustomCode },
        { field: 'addStorageBatchCode', title: '入库批次' },
        { field: 'wlCode', title: '物料号' },
        { field: 'wlms', title: '物料名称' },
        { field: 'ckmc', title: '物料规格' },
        { field: 'xbcLocationCode', title: '库位' },
        // { field: 'productBatchCode', title: '产品批号', visible: this.conf.isRegProduBatch },
        // { field: 'materialBatchCode', title: '来料批次', visible: this.conf.isRegLlBatch },
        // { field: 'effectiveDate', title: '有效期', visible: this.conf.isTerm },
        { field: 'dw', title: '单位' },
        { field: 'remainNum', title: '库存数量' }
        // { field: 'remark', title: '备注' }
      ]
      // if (this.filter.wllb !== null) {
      //   this.mtableColumn = [
      //     { type: 'checkbox', width: 50 },
      //     { type: 'seq', width: 60 },
      //     { field: 'stockInId', title: '入库id', visible: false },
      //     { field: 'materialCode', title: '物料编码', visible: this.conf.isProduceNumb },
      //     { field: 'customerCode', title: '客户代码', visible: this.conf.showCustomCode },
      //     { field: 'addStorageBatchCode', title: '入库批次' },
      //     { field: 'wlCode', title: '物料号' },
      //     { field: 'wlms', title: '物料名称' },
      //     { field: 'wlgg', title: '物料规格' },
      //     { field: 'xbcLocationCode', title: '库位' },
      //     { field: 'productBatchCode', title: '产品批号', visible: this.conf.isRegProduBatch },
      //     { field: 'materialBatchCode', title: '来料批次', visible: this.conf.isRegLlBatch },
      //     { field: 'effectiveDate', title: '有效期', visible: this.conf.isTerm },
      //     { field: 'dw', title: '单位' },
      //     { field: 'remainNum', title: '库存数量', visible: !this.conf.isSingle },
      //     { field: 'remark', title: '备注' }
      //   ]
      this.mfilter.wlId = row.matterrialId
      this.mfilter.kwId = row.locationId
      this.modalShow = !this.modalShow

      if (this.$refs.mGrid) {
        this.$nextTick(() => {
          this.$refs.mGrid.commitProxy('reload')
        })
      }

      // } else {
      //   this.$XModal.message({ status: 'warning', message: '请选择物料类别！' })
      // }

      // loading.close()
    },
    closeEditForm() {
    },
    closeAddForm() {
    },
    // 编辑验证
    editFormValidate: function() {
      let isValid = false
      this.$refs.editForm.validate(valid => {
        isValid = valid
      })
      return isValid
    },
    // 新增验证
    addFormValidate: function() {
      let isValid = false
      this.$refs.addForm.validate(valid => {
        isValid = valid
      })
      return isValid
    },
    editclose() {
      this.editFormVisible = false
    },
    async getxbcLocationList(id) {
      const res = await getxbcLocationList({ id: id })
      if (res && res.success) {
        this.xbcLocationList = res.data
        this.addForm.xbcLocationId = null
        this.editForm.xbcLocationId = null
      }
    },
    async editGetxbcLocationList(id) {
      const res = await getxbcLocationList({ id: id })
      if (res && res.success) {
        this.xbcLocationList = res.data
      }
    },
    selsChange: function(sels) {
      this.sels = sels
    }
  }
}
</script>
